﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web.Services;
using drules.dates.library;

namespace DatesWcfService
{
    [WebService(Description = "Date rule web service, providing dates for a given rule.")]
    public class DatesService : IDatesService
    {
        #region IDatesService Members
        [WebMethod(EnableSession = false, BufferResponse = true, CacheDuration = 60, Description = "Returns the names of the defined rules")]
        public String[] GetRuleNames()
        {
            return DateExpression.Instance.RuleNames;
        }

        [WebMethod(EnableSession = false, BufferResponse = true, CacheDuration = 60, Description = "Returns the date resulting from the rule")]
        public DateTime? GetDate(string ruleName, DateTime? refDate)
        {
            return DateExpression.Parse(ruleName).GetDate(refDate.GetValueOrDefault(DateTime.Today).ToLocalTime().Date);
        }

        [WebMethod(EnableSession = false, BufferResponse = true, CacheDuration = 60, Description = "Returns the next days in the date rule")]
        public DateTime[] GetDates(string ruleName, DateTime refDate, int? limit)
        {
            List<DateTime> result = new List<DateTime>(); 
            IDateRule rule = DateExpression.Parse(ruleName);

            if (null != rule)
                result.AddRange(rule.GetDates(refDate.ToLocalTime().Date, limit.GetValueOrDefault(1000)));

            return result.ToArray();
        }

        [WebMethod(EnableSession = false, BufferResponse = true, CacheDuration = 60, Description = "Returns the days in the rule between two dates")]
        public DateTime[] GetDatesBetween(string ruleName, DateTime fromRefDate, DateTime toRefDate)
        {
            List<DateTime> result = new List<DateTime>(); 
            IDateRule rule = DateExpression.Parse(ruleName);            

            if (null != rule)
                result.AddRange(rule.GetDatesBetween(fromRefDate.ToLocalTime().Date, toRefDate.ToLocalTime().Date));

            return result.ToArray();
        }
        #endregion
    }
}